//**************************************************************************
// Copyright 2008 Peter Project (http://www.codeplex.com/peter)
//
// License : GNU General Public License (GPL)
// For full text of the license please goto:
// http://www.gnu.org/licenses/gpl-2.0.html
//
// This code is provided on an AS IS basis, with no WARRANTIES,
// CONDITIONS or GUARANTEES of any kind.
//
//		File: ctrlInternetBrowser.cs
//
//**************************************************************************

using System;
using System.ComponentModel;
using System.Drawing;
using System.Resources;
using System.Text.RegularExpressions;
using System.Web;
using System.Windows.Forms;
using mshtml;
using PeterInterface;
using WeifenLuo.WinFormsUI.Docking;

namespace InternetBrowser
{
    ///<summary>Control that provides a web browser experience</summary>
    public partial class ctrlInternetBrowser : DockContent, IPeterPluginTab
    {
        private readonly Webber m_Webber;
        private IPeterPluginHost m_Host;

        ///<summary>Default Ctor - initializes control</summary>
        public ctrlInternetBrowser()
        {
            m_Webber = new Webber();
            m_Webber.Dock = DockStyle.Fill;
            Controls.Add(m_Webber);
            m_Webber.GoHome();

            InitializeComponent();

            TabText = "Internet ctrlFileBrowser";
            toolStrip1.Resize += ResizeToolStrip;
            m_Webber.Navigated += WebNavigated;
            m_Webber.NewWindow += WebNewWindow;
            cmbAddress.KeyDown += WebKeyDown;
            txtGoogle.KeyDown += GoogleKeyDown;
            tsbBack.Enabled = m_Webber.CanGoBack;
            tsbForward.Enabled = m_Webber.CanGoForward;
        }

        private void WebNewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
            WebBrowser web = sender as WebBrowser;
            if (web != null)
            {
                HtmlElement htmlObj = web.Document.ActiveElement;
                HTMLAnchorElementClass anchor = (HTMLAnchorElementClass) htmlObj.DomElement;
                ctrlInternetBrowser browser = new ctrlInternetBrowser();
                ResourceManager mngr = new ResourceManager("InternetBrowser.InternalImages", GetType().Assembly);
                browser.Icon = Icon.FromHandle(((Bitmap) mngr.GetObject("Icon")).GetHicon());
                browser.Navigate(anchor.href);
                m_Host.AddDockContent(browser, DockState.Document);
            }
            else
            {
                Host.Trace("Could not find WebBrowser window to duplicate.");
            }
        }

        private void GoogleKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                tsbSearch_Click(sender, null);
            }
        }

        private void WebKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                tsbGo_Click(sender, null);
            }
        }

        private void WebNavigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            TabText = m_Webber.Document.Title;
            if (TabText.Trim() == string.Empty)
            {
                TabText = "Internet ctrlFileBrowser";
            }
            cmbAddress.Text = m_Webber.Document.Url.ToString();
            if (!cmbAddress.Items.Contains(cmbAddress.Text))
            {
                cmbAddress.Items.Add(cmbAddress.Text);
            }

            tsbBack.Enabled = m_Webber.CanGoBack;
            tsbForward.Enabled = m_Webber.CanGoForward;
        }

        private void ResizeToolStrip(object sender, EventArgs e)
        {
            int w = 0;
            foreach (ToolStripItem tsi in toolStrip1.Items)
            {
                w += tsi.Width;
            }
            w -= cmbAddress.Width;
            w += 16;
            if (w > 7)
            {
                cmbAddress.Width = toolStrip1.Width - w;
            }
        }

        protected override string GetPersistString()
        {
            return GetType() + "|" + cmbAddress.Text;
        }

        #region IPeterPluginTab Members

        ///<summary>
        ///</summary>
        public void Save()
        {
        }

        public void SaveAs(string filePath)
        {
        }

        public void Cut()
        {
            m_Webber.Cut();
        }

        public void Copy()
        {
            m_Webber.Copy();
        }

        public void Paste()
        {
            m_Webber.Paste();
        }

        public void Undo()
        {
        }

        public void Redo()
        {
        }

        public void Delete()
        {
            m_Webber.Delete();
        }

        public void Duplicate()
        {
        }

        public void Print()
        {
        }

        public void SelectAll()
        {
            m_Webber.SelectAll();
        }

        public bool CloseTab()
        {
            Close();
            return true;
        }

        public IPeterPluginHost Host
        {
            get { return m_Host; }

            set { m_Host = value; }
        }

        public string FileName
        {
            get
            {
                if (m_Webber.Document.Url.ToString() != string.Empty)
                {
                    return m_Webber.Document.Url.ToString();
                }
                return "";
            }
        }

        public string Selection
        {
            get { return m_Webber.Selection; }
        }

        public bool AbleToUndo
        {
            get { return false; }
        }

        public bool AbleToRedo
        {
            get { return false; }
        }

        public bool AbleToPaste
        {
            get { return true; }
        }

        public bool AbleToCut
        {
            get { return false; }
        }

        public bool AbleToCopy
        {
            get { return true; }
        }

        public bool AbleToSelectAll
        {
            get { return true; }
        }

        public bool AbleToSave
        {
            get { return false; }
        }

        public bool AbleToDelete
        {
            get { return false; }
        }

        public bool NeedsSaving
        {
            get { return false; }
        }

        public void MarkAll(Regex reg)
        {
        }

        public bool FindNext(Regex reg, bool searchUp)
        {
            return m_Webber.FindNext(reg.ToString());
        }

        public void ReplaceNext(Regex reg, string replaceWith, bool searchUp)
        {
        }

        public void ReplaceAll(Regex reg, string replaceWith)
        {
        }

        public void SelectWord(int line, int offset, int wordLeng)
        {
        }

        #endregion

        private void tsbBack_Click(object sender, EventArgs e)
        {
            if (m_Webber.CanGoBack)
            {
                m_Webber.GoBack();
            }
        }

        private void tsbForward_Click(object sender, EventArgs e)
        {
            if (m_Webber.CanGoForward)
            {
                m_Webber.GoForward();
            }
        }

        private void tsbStop_Click(object sender, EventArgs e)
        {
            m_Webber.Stop();
        }

        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            m_Webber.Refresh();
        }

        private void tsbHome_Click(object sender, EventArgs e)
        {
            m_Webber.GoHome();
        }

        private void tsbGo_Click(object sender, EventArgs e)
        {
            if (cmbAddress.Text.Trim() != string.Empty)
            {
                cmbAddress.Text = cmbAddress.Text.Trim();
                m_Webber.Navigate(cmbAddress.Text);
            }
        }

        private void tsbSearch_Click(object sender, EventArgs e)
        {
            if (txtGoogle.Text.Trim() == string.Empty)
            {
                m_Webber.Navigate("http://www.google.com");
            }
            else
            {
                m_Webber.Navigate("http://www.google.com/search?q=" +
                                  HttpUtility.UrlEncode(txtGoogle.Text.Trim()));
            }
        }

        ///<summary>Navigate to the <paramref name="url"/> provided.</summary>
        ///<param name="url"></param>
        public void Navigate(string url)
        {
            cmbAddress.Text = url;
            tsbGo_Click(null, null);
        }

        ///<summary>Search for the <paramref name="text"/> provided.</summary>
        ///<param name="text"></param>
        public void Search(string text)
        {
            txtGoogle.Text = text;
            tsbSearch_Click(null, null);
        }
    }
}